package com.hpc.Filter;

import Utils.JWTUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class loginFilter implements GlobalFilter, Ordered {
    @Resource
    private RedisTemplate redisTemplate;
    @Value("${filter.excludedPath}")
    private String excludedPath;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入登录拦截。。。。。。。");
        log.info("排除拦截路径："+excludedPath);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("请求URI为："+path);
        String token = request.getHeaders().getFirst("token");
        log.info("token为："+token);
        String userId="";
        if(!StringUtils.isEmpty(token)){
            DecodedJWT decodejwt = JWTUtil.decodejwt(token);
             userId = decodejwt.getClaim("userid").asString();
            //校验成功后将解析出来的工号放入请求头中
            exchange.getRequest().mutate().header("userId", userId).build();
        }
        List<String> excludedPaths= Arrays.asList(excludedPath.split(","));
        for (String s : excludedPaths) {
            if (path.contains(s)){
                return chain.filter(exchange);
            }
        }
        if (!(StringUtils.isEmpty(token))){
            if (redisTemplate.hasKey(userId)){
                String token_redis=(String)redisTemplate.opsForValue().get(userId);
                if (token.equalsIgnoreCase(token_redis)){
                    //更新token在redis中的时间,30分钟
                    redisTemplate.expire(userId,30, TimeUnit.MINUTES);
                    return chain.filter(exchange);
                }
            }
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        /////////////return response.setComplete();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String errorJson = "{\"code\": 401, \"message\": \"Unauthorized\"}";
        byte[] errorBytes = errorJson.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(errorBytes);
        return response.writeWith(Mono.just(buffer));
//        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
